import { css } from "@emotion/css";
import {
  Breadcrumb,
  Button,
  DatePicker,
  Descriptions,
  Form,
  Input,
  Message,
  Select,
  Table,
  Tag,
} from "@arco-design/web-react";
import { usePagination } from "../../hooks/usePagination.ts";
import { RiskType, SearchRiskTypeParams } from "../../api/types/elder-risk.ts";
import { useAPI } from "../../hooks/useAPI.ts";
import { useEffect, useState } from "react";
import { Link } from "../../components/Link";
import {
  IconDown,
  IconRefresh,
  IconRight,
  IconSync,
} from "@arco-design/web-react/icon";
import {
  findRisk,
  timestampToLocalTime,
} from "../../components/ElderReport/ActivityListAndRecord.tsx";
import {
  reportName,
  reportResult,
  reportTime,
} from "../../components/ElderReport/RiskHandleRecord.tsx";
import { ViewVideoRecordModal } from "../../components/ViewVideoRecordModal";
import { useQuery } from "react-query";
import { elderListParams } from "../../components/BindElderAndRoomModal";
import { bed } from "./elderManagement.tsx";
import { CameraStatus } from "../../api/types/camera.ts";
import { CameraColorMap, CameraTextMap } from "../../hooks/useCameraStatus.ts";
import dayjs from "dayjs";

export default function Risk() {
  const api = useAPI();
  const [dateRange, setDateRange] = useState<string[] | undefined>([
    dayjs().subtract(100, "day").format("YYYY-MM-DD"), // Yesterday
    dayjs().format("YYYY-MM-DD"), // Today
  ]);
  const { pagination, pageNum, pageSize, setTotal } = usePagination();
  const [formRef] = Form.useForm<SearchRiskTypeParams>();
  const [data, setData] = useState([]);
  const [search, setSearchValues] = useState("");
  const [userId, setUserId] = useState("");
  const [viewUserId, setViewUserId] = useState("");
  const [refresh, setRefresh] = useState(false);
  const [isLoading, setIsLoading] = useState(true);
  const [suid, setSuid] = useState("");
  const [action, setAction] = useState(null);
  const [report, setReport] = useState("null");
  const [id, setId] = useState<number>(-1);
  const [time, setTime] = useState("");

  const { data: elderList } = useQuery(
    ["query-elder-list", elderListParams],
    async () => {
      const response = await api.getSystemUserList({ ...elderListParams });
      if (!response.data.data) {
        throw new Error("No Data");
      }
      return response.data.data;
    },
  );

  useEffect(() => {
    setIsLoading(true);
    api
      .getRiskAllList({
        actionId: "",
        endDate: dateRange ? dateRange[1] : "",
        length: pageSize,
        riskLevel: RiskType.HighAndMiddle,
        search: search,
        start: pageNum - 1,
        startDate: dateRange ? dateRange[0] : "",
        userId: userId || "",
      })
      .then((response) => {
        setData(
          response.data?.data.map((row: any, index: number) => ({
            index: index + 1 + (pageNum - 1) * pageSize, // Add index starting from 1
            ...row,
          })),
        );
        setTotal(response.data?.recordsTotal || 0);
        setIsLoading(false);
      })
      .catch((error) => {
        if (error instanceof Error) {
          Message.error(error.message);
        } else {
          Message.error("操作失败，请稍后重试");
        }
      });
  }, [search, userId, refresh, pageSize, pageNum, dateRange]);

  const [isOpenViewVideoRecordModal, setIsViewVideoRecordModal] =
    useState(false);

  const deleteRecord = (id: number, suid: string) => {
    api
      .deleteRiskProcessingLog({
        id,
        userId: viewUserId,
        suid,
        data: {
          pics: "", files: "",
          method: 0,
          report: {
            userId: window.localStorage.getItem("loggedUserId"),
            nickName: window.localStorage.getItem("loggedNickName"),
          },
          time: dayjs().format("YYYY-MM-DD HH:MM:s"),
        },
      })
      .then((r) => {
        if (r.data.code == "3001") {
          Message.info("操作成功");
          setRefresh(!refresh);
        } else {
          Message.info("操作失败");
        }
      });
  };

  return (
    <div>
      <ViewVideoRecordModal
        videoList={suid}
        id={id}
        userId={viewUserId}
        report={report}
        visible={isOpenViewVideoRecordModal}
        eventTime={time}
        action={action}
        onClose={() => setIsViewVideoRecordModal(false)}
        refresh={() => setRefresh(!refresh)}
        deleteRecord={deleteRecord}
      />

      <div
        className={css`
          width: 100%;
          display: flex;
          justify-content: space-between;
          align-items: center;
        `}
      >
        <Breadcrumb
          className={css`
            padding: 12px;
            border-radius: 1px;
            font-weight: bold;
            border-left: 5px solid rgb(var(--primary-6));
            margin-bottom: 20px;
          `}
          separator={<IconRight />}
        >
          <Breadcrumb.Item style={{ fontWeight: 400 }}>
            <Link
              to="/homepage/risk"
              style={{
                textDecoration: "none",
                transition: "color 0.3s",
                fontWeight: "bold",
                fontSize: "15px",
              }}
            >
              风险管理
            </Link>
          </Breadcrumb.Item>
        </Breadcrumb>
      </div>
      <div
        className={css`
          width: 100%;
          display: flex;
          justify-content: space-between;
          align-items: center;
        `}
      >
        <Form form={formRef} layout="inline">
          <Form.Item field="key" label="搜索：">
            <Input.Search
              value={search}
              onChange={(v) => {
                setSearchValues(v);
              }}
              allowClear
              placeholder="请输入关键字"
              style={{ width: "200px" }}
            />
          </Form.Item>
          <Form.Item label="按长辈查询：" field="userId">
            <Select
              style={{ width: "200px" }}
              placeholder="请选择长辈"
              allowClear
              options={elderList?.rows.map((item) => ({
                label: item.nickName,
                value: item.userId,
              }))}
              allowCreate
              showSearch
              filterOption={(input, option) =>
                option?.props.children
                  .toLowerCase()
                  .includes(input.toLowerCase())
              }
              onChange={(value) => {
                setUserId(value);
                setIsLoading(true);
              }}
            />
          </Form.Item>
          <Form.Item label="按时间查询：" field="date">
            <DatePicker.RangePicker
              onChange={(e) => {
                setDateRange(e);
              }}
              defaultValue={dateRange}
              disabledDate={(current) => current.isAfter(dayjs())}
              shortcuts={[
                {
                  text: "上一周",
                  value: () => [dayjs(), dayjs().subtract(1, "week")],
                },
                {
                  text: "上一个月",
                  value: () => [dayjs(), dayjs().subtract(1, "month")],
                },
                {
                  text: "上一年",
                  value: () => [dayjs(), dayjs().subtract(1, "year")],
                },
              ]}
              style={{ width: "250px" }}
            />
          </Form.Item>
          <Form.Item>
            <Button
              type="outline"
              htmlType="button"
              onClick={() => {
                formRef.resetFields();
                setSearchValues("");
                setDateRange(undefined);
                setRefresh(!refresh);
              }}
            >
              <IconRefresh />
              重置
            </Button>
          </Form.Item>
        </Form>

        <Button
          type="primary"
          size="small"
          onClick={() => {
            setRefresh(!refresh);
          }}
        >
          <IconSync />
          刷新
        </Button>
      </div>

      <Table
        loading={isLoading}
        data={data}
        className={css`
          margin-top: 16px;
        `}
        expandedRowRender={(record) => {
          return (
            <Descriptions
              colon=" :"
              layout="inline-horizontal"
              title={`${record.nickName}的风险处理结果`}
              data={[
                { label: "处理时间", value: reportTime(record.report) },
                { label: "处理人", value: reportName(record.report) },
                { label: "处理结果", value: reportResult(record.report) },
                { label: "楼管", value: record.manager },
                { label: "楼管联系方式", value: record.managerPhonenumber },
              ]}
            />
          );
        }}
        expandProps={{
          icon: ({ expanded, record, ...restProps }) =>
            expanded ? (
              <button {...restProps}>
                <IconDown />
              </button>
            ) : (
              <button {...restProps}>
                <IconRight />
              </button>
            ),
          width: 150,
          columnTitle: "查看处理结果",
          expandRowByClick: true,
          rowExpandable: (record) =>
            record.report !== null || record.report !== "null",
        }}
        pagination={pagination}
        rowKey="id"
        columns={[
          {
            title: "序号",
            dataIndex: "index",
            key: "index",
            align: "center", // Center the cell content
            headerAlign: "center", // Center the header content
            sorter: (a, b) => a.index - b.index,
          },
          {
            title: "姓名",
            dataIndex: "nickName",
            key: "nickName",
            align: "center", // Center the cell content
            headerAlign: "center", // Center the header content
          },
          {
            title: "生活管家",
            dataIndex: "manager",
            key: "manager",
            align: "center", // Center the cell content
            headerAlign: "center", // Center the header content
          },
          {
            title: "摄像头信息",
            dataIndex: "cameraStatus",
            key: "cameraStatus",
            align: "center", // Center the cell content
            headerAlign: "center", // Center the header content
            render: (record: CameraStatus) =>
              record ? (
                <Tag color={CameraColorMap[record]}>
                  {CameraTextMap[record]}
                </Tag>
              ) : (
                ""
              ),
          },
          {
            title: "位置",
            dataIndex: "buildingName",
            key: "buildingName",
            align: "center", // Center the cell content
            headerAlign: "center", // Center the header content
            render: (buildingName: any, row: any) =>
              buildingName === null
                ? "未绑定"
                : `${buildingName}-${row.floorName}-${row.roomName}${row.location
                  ? "-" + bed[row.location as keyof typeof bed]
                  : ""
                }`,
          },
          {
            title: "风险等级",
            dataIndex: "riskLevel",
            key: "riskLevel",
            align: "center", // Center the cell content
            headerAlign: "center", // Center the header content
            render: (riskLevel) => findRisk(riskLevel),
          },
          {
            title: "警报时间",
            dataIndex: "startTime",
            key: "startTime",
            align: "center", // Center the cell content
            headerAlign: "center", // Center the header content
            render: (startTime) => (
              <span>
                {startTime ? timestampToLocalTime(startTime * 1000.0) : ""}
              </span>
            ),
          },
          {
            title: "警报内容",
            dataIndex: "actCn",
            key: "actCn",
            align: "center", // Center the cell content
            headerAlign: "center", // Center the header content
          },
          {
            title: "处理",
            dataIndex: "report",
            key: "report",
            align: "center", // Center the cell content
            headerAlign: "center", // Center the header content
            render: (report) => {
              if (report === null || report === "null")
                return <Tag color="red"> 未处理 </Tag>;
              else return <Tag color="green"> 已处理 </Tag>;
            },
          },
          {
            title: "操作",
            dataIndex: "userId",
            key: "userId",
            align: "center", // Center the cell content
            headerAlign: "center", // Center the header content
            width: 180,
            render: (record: any, row: any) => {
              const suid = JSON.parse(row.suid);
              return suid?.length > 0 ? (
                <Button
                  size="small"
                  onClick={(e) => {
                    e.preventDefault();
                    e.stopPropagation();
                    setIsViewVideoRecordModal(true);
                    setSuid(suid.length > 0 ? suid[0] : "");
                    setReport(row.report);
                    setId(row.actionId);
                    setViewUserId(record);
                    setAction(row.actCn);
                    setTime(timestampToLocalTime(row.startTime * 1000.0));
                  }}
                >
                  查看回放并处理
                </Button>
              ) : (
                <div>无</div>
              );
            },
          },
        ]}
      />
    </div>
  );
}
